﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Drawing;
using System.Text;
using System.IO;
using System.Threading;
using System.Xml;
using System.Windows.Forms;
using DevComponents.DotNetBar;

using Shine.ManageUser;
using Shine.Framework;
using Shine.Viewer;
using System.Runtime.InteropServices;
using SuperMap.Data;
using SuperMap.Realspace;
using SuperMap.Mapping;

namespace Shine.Main
{
    public partial class MainFramework : Office2007RibbonForm
    {
        IApplication pApplication = new ApplicationClass();
        ViewSpotListUserForm viewspotPanel = null;

        private const int WM_ENTERSIZEMOVE = 0x231;
        private const int WM_EXITSIZEMOVE = 0x232;
      
        [DllImport("user32.dll")]
        public static extern long SetCapture(int hwnd);
        [DllImport("user32.dll")]
        public static extern long ReleaseCapture();
       // System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        System.Timers.Timer timer = new System.Timers.Timer();
        IUser m_User;
        private readonly string BOTTOMHIDE =Application.StartupPath +
                    (System.Configuration.ConfigurationManager.AppSettings.Get("Folder") == null || System.Configuration.ConfigurationManager.AppSettings.Get("Folder").Trim() == "" ? "" : ("\\" + System.Configuration.ConfigurationManager.AppSettings.Get("Folder"))) +
                    "\\Config\\hidetemp";
   
        public User User
        {
            set
            {
                m_User = value;
            }
        }
       
        SuperMap.UI.MapControl m_mapCtrl;
        SuperMap.UI.LayersControl m_lyrContrl;
        SuperMap.UI.LayersTree m_lyrTree;
        SuperMap.UI.SceneControl  m_sceneControl;
        SuperMap.UI.SceneControl m_sceneControl2;
        SuperMap.UI.WorkspaceControl m_wksControl;
        SuperMap.Data.Workspace m_workspace;

        public MainFramework()
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; 
            this.Visible = false;
          
            Thread splashthread = new Thread(new ThreadStart(SplashScreen.ShowSplashScreen));
            splashthread.IsBackground = true;
            splashthread.Start();

            this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
            this.UpdateStyles();
            InitializeComponent();

            string sysName = System.Configuration.ConfigurationManager.AppSettings.Get("SysName");
            string strFile = Application.StartupPath + "\\"+sysName+".xml";
            if (File.Exists(strFile) == false)
            {
                //ZJGIS.ADF.BaseClasses.ControlUtility.ShowInfomationMsgbox("运行单机版系统需要界面定义文件,系统安装路径下不存在'"+sysName+".xml'文件！");
                System.Diagnostics.Process.GetCurrentProcess().Kill();
                return;
            }
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(strFile);
            PrivilegeGroup rolecontent = new PrivilegeGroup();
            rolecontent.Xml = xmlDocument.InnerXml;
            List<IPrivilegeGroup> group = new List<IPrivilegeGroup>();
            foreach (IPrivilegeElement element in rolecontent.GetChilds())
            {
                if (element is IPrivilegeGroup)
                {
                    group.Add(element as IPrivilegeGroup);
                }
            }

            m_User = new User();
            m_User.Name = "单机版用户";
            m_User.PrivilegeGroups = group;
            strFile = Application.StartupPath +
                (System.Configuration.ConfigurationManager.AppSettings.Get("Folder") == null || System.Configuration.ConfigurationManager.AppSettings.Get("Folder").Trim() == "" ? "" : ("\\" + System.Configuration.ConfigurationManager.AppSettings.Get("Folder"))) +
                "\\Config\\tocmenuconfig.xml";

            if (File.Exists(strFile))
            {
                xmlDocument = new XmlDocument();
                xmlDocument.Load(strFile);
                rolecontent = new PrivilegeGroup();
                rolecontent.Xml = xmlDocument.InnerXml;
                List<IPrivilegeGroup> tocMenugroup = new List<IPrivilegeGroup>();
                foreach (IPrivilegeElement element in rolecontent.GetChilds())
                {
                    if (element is IPrivilegeGroup)
                    {
                        tocMenugroup.Add(element as IPrivilegeGroup);
                    }
                }
                m_User.ContentMenContent = tocMenugroup;
            }          
                  
           // Thread.Sleep(100);
          
           
            Text = System.Configuration.ConfigurationManager.AppSettings.Get("SysName");          
        }

        protected override void WndProc(ref System.Windows.Forms.Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == WM_ENTERSIZEMOVE)
            {
             //   m_MapControl.SuppressResizeDrawing(true, 0);
            }
            else if (m.Msg == WM_EXITSIZEMOVE)
            {
              //  m_MapControl.SuppressResizeDrawing(false, 0);
            }
        }
      
        void MainFramework_Load(object sender1, System.EventArgs e1)
        {
            SystemInitialize();

            ribbonControl1.SelectedRibbonTabItem = ribbonControl1.Items[1] as RibbonTabItem;
            ribbonControl1.SelectedRibbonTabItem = ribbonControl1.Items[0] as RibbonTabItem;
            SplashScreen.CloseSplashScreen();
            this.TopMost = true;
            // this.TopMost = false;
            m_sceneControl.Focus();
       



    }

        private void SystemInitialize()
        {
            //this.Hide();
            try
            {                            
                #region 控件初始化
                // 全屏显示
                (pApplication as ApplicationClass).OnFullScreenEvent += MainFramework_OnFullScreenEvent;

                m_sceneControl = new SuperMap.UI.SceneControl(SceneType.Globe);
                m_sceneControl.Dock = DockStyle.Fill;
                m_sceneControl.KeyDown += m_sceneControl_KeyDown;
                //m_sceneControl.DoubleClick += M_sceneControl_DoubleClick;
                panelDockContainer2.Controls.Add(m_sceneControl);

                m_sceneControl2 = new SuperMap.UI.SceneControl(SceneType.Globe);
                m_sceneControl2.Dock = DockStyle.Fill;
                m_sceneControl2.Visible = false;
                panelDockContainer2.Controls.Add(m_sceneControl2);

                m_mapCtrl = new SuperMap.UI.MapControl();
                m_mapCtrl.Dock = DockStyle.Fill;               
                panelDockContainer2.Controls.Add(m_mapCtrl);
                m_mapCtrl.Visible = false;             
                
                m_lyrContrl = new SuperMap.UI.LayersControl();
                m_lyrContrl.Dock = DockStyle.Fill;
                dockPanelToc.Controls.Add(m_lyrContrl);

                m_wksControl = new SuperMap.UI.WorkspaceControl();
                m_wksControl.Dock = DockStyle.Fill;
                dockPanelResource.Controls.Add(m_wksControl);
                
                // 增加视点面板
                viewspotPanel = new ViewSpotListUserForm(pApplication);
                viewspotPanel.Dock = System.Windows.Forms.DockStyle.Fill;
                viewspotPanel.AutoScroll = true;
                viewspotPanel.AutoSize = true;
                viewspotPanel.BorderStyle = BorderStyle.None;
                dockPanelViewspot.Controls.Add(viewspotPanel);

                AddData();
                (pApplication as IFramework).BindControls(m_mapCtrl, m_sceneControl, m_sceneControl2, m_wksControl, m_lyrContrl, true);

                #endregion
                #region BarManager
                (pApplication as IFramework).User = m_User;                
                (pApplication as IFramework).DockManager.MainForm = this;
                (pApplication as IFramework).DockManager.DockManager = this.dotNetBarManager1;
                (pApplication as IFramework).BarManager.CommandPoolEx.Hook = pApplication;
                (pApplication as IFramework).BarManager.OnItemClickEvent += new OnItemClickEventHandler(BarManager_OnItemClickEvent);
                (pApplication as IFramework).BarManager.CreateBar(ribbonControl1, (pApplication as IFramework).User.PrivilegeGroups);
                (pApplication as IFramework).MdiForm = this;
              
                // this.tabControl1.SelectedTabChanged += new TabStrip.SelectedTabChangedEventHandler(tabControl1_SelectedTabChanged);
                pApplication.StatusBar.StatusBar = this.barStauts;
                // m_sceneControl2.ContextMenu = new ContextMenu();
                // m_sceneControl2.ContextMenu.MenuItems.Add("加载模型", MnuAddModel_Click);

                #endregion             
                ReadLayoutConfig();

                #region 设置风格
                string strStyle = System.Configuration.ConfigurationManager.AppSettings.Get("SystemStyle");
                if (strStyle != null && strStyle.Trim() != "")
                {
                   bool bln=  Enum.IsDefined(typeof(eStyle), strStyle.Trim());
                   if (bln)
                   {
                       eStyle style = (eStyle)Enum.Parse(typeof(eStyle), strStyle.Trim());
                       StyleManager.ChangeStyle(style, Color.Empty);
                       foreach (ButtonItem item in btnChangeStyle.SubItems)
                       {
                           if (item.CommandParameter.ToString() == strStyle)
                           {
                               item.Checked = true;
                               break;
                           }
                       }
                   }
                }
                #endregion

                
                 
               // this.WindowState = FormWindowState.Maximized;
              //  Thread.Sleep(100);
                Thread t = new Thread(ThreadProc);
                t.Start();
               
                this.Visible = true;
                this.Focus();
                
                
            }
            catch (Exception ex)
            {
                SplashScreen.CloseSplashScreen();
                this.Visible = true;
               // ZJGIS.ADF.BaseClasses.ControlUtility.ShowInfomationMsgbox("系统初始化出现错误，错误信息:" + ex.Message);              
            }
            finally
            {
                this.Cursor = Cursors.Default;              
            }
        }

        private void MainFramework_OnFullScreenEvent(object sender, EventArgs e)
        {
            this.leftbar.Hide();
            this.ribbonControl1.Hide();
            this.barStauts.Hide();
        }

        private void MnuAddModel_Click(object sender, EventArgs e)
        {
            if((pApplication as IFramework).IsSceneCompare)
            {
                System.Windows.Forms.OpenFileDialog dlg = new OpenFileDialog();
                dlg.Multiselect = false;
                dlg.Filter = "文件数据源(*.udb)|*.udb";

                if (dlg.ShowDialog() != DialogResult.OK) return;
                try
                {
                    string file = dlg.FileName;
                    DatasourceConnectionInfo datasourceInfo = new DatasourceConnectionInfo();
                    datasourceInfo.EngineType = EngineType.UDB;
                    datasourceInfo.Server = dlg.FileName;
                    Datasource datasource = m_wksControl.WorkspaceTree.Workspace.Datasources.Open(datasourceInfo);

                    foreach (Dataset dst in datasource.Datasets)
                    {
                        if (dst.Type == DatasetType.Model)
                        {
                            // Layer3DSetting  
                            // Layer3D lyr= (m_Application as IFramework).SceneControl.Scene.Layers.Add(file+"\\"+dst.Name,  Layer3DType.Model, true);
                            Layer3DSettingVector setting = new Layer3DSettingVector();
                            setting.Style.AltitudeMode = AltitudeMode.Absolute;
                            Layer3D lyr = m_sceneControl2.Scene.Layers.Add(dst, setting, true);
                            // m_sceneControl2.Focus();
                            m_sceneControl2.Scene.EnsureVisible(lyr);
                            m_sceneControl2.Scene.Refresh();
                            m_sceneControl.Scene.Camera = m_sceneControl2.Scene.Camera;
                            break;
                            
                        }
                    }
                }catch(System.Exception ee)
                {
                    MessageBox.Show(ee.Message);
                }
            }
        }

        private void M_sceneControl_DoubleClick(object sender, EventArgs e)
        {
            Selection3D[] s = m_sceneControl.Scene.FindSelection(true);
            if(s.Length==1)
            {
                FrmQuery frm = FrmQuery.Instance();
                //frm.Application = m_Application;
                if (frm.Visible == false)
                {
                    frm.Show(this);
                }
                frm.ShowAttributes(s[0].ToRecordset());

               
            }
        }

        private void AddData()
        {
            try
            {
                m_workspace = new Workspace();
                string file = System.Configuration.ConfigurationManager.AppSettings["workspace"];
               // string scene = System.Configuration.ConfigurationManager.AppSettings["defaultScene"];
                WorkspaceConnectionInfo conInfo = new WorkspaceConnectionInfo(file);
                if (System.IO.Path.GetExtension(file).ToLower() == ".sxwu")
                {
                    conInfo.Type = WorkspaceType.SXWU;
                }
                else conInfo.Type = WorkspaceType.SMWU;
                m_workspace.Open(conInfo);

                m_sceneControl.Scene.Workspace = m_workspace;
                // m_sceneControl.Scene.Open(m_workspace.Scenes[ m_workspace.Scenes.IndexOf(scene)]);
                if (m_workspace.Scenes.Count > 0)
                    m_sceneControl.Scene.Open(m_workspace.Scenes[0]);


                m_sceneControl2.Scene.Workspace = m_workspace;

                m_mapCtrl.Map.Workspace = m_workspace;
                if (m_workspace.Maps.Count > 0) m_mapCtrl.Map.Open(m_workspace.Maps[0]);
                m_lyrContrl.Scene = m_sceneControl.Scene;
                m_wksControl.WorkspaceTree.Workspace = m_workspace;               
            }
            catch (System.Exception ee)
            {
            }
        }

        public void ThreadProc()
        {
            try
            {
                //timer.Tick += delegate(object sender, EventArgs e)
                //{
                //    timer.Stop();
                //    (pApplication as IFramework).BarManager.CommandPoolEx.UpdateCommandState();
                //    timer.Start();
                //};
                timer.Enabled = true;
                timer.Interval = 500;
              

                timer.Elapsed += delegate
                {
                    timer.Stop();
                    (pApplication as IFramework).BarManager.CommandPoolEx.UpdateCommandState();
                    timer.Start();

                    this.TopMost = false;
                };
                timer.Start();
            }
            catch (Exception ex)
            {
            }
        }

        void BarManager_OnItemClickEvent(object obj)
        {
            (pApplication as IFramework).ExecuteCommand(obj as Shine.Framework.ICommand);
        }
        
        public void SetCurrentCoords(string text)
        {           
            lblCoordinate.Text = text;
           
        }      
        public void ShowWorkingStatus(bool isWorking)
        {
            //if (isWorking)
            //    timer.Stop();
            //else
            //    timer.Start();
            //if (isWorking)
            //    pApplication.StatusBar.ShowProgressBar("");
            //else
            //    pApplication.StatusBar.HideProgressBar();
        }

        #region TabChanged
        private void tabControl1_SelectedTabChanged(object sender, TabStripTabChangedEventArgs e)
        {                     
          //timer.Stop();
          //  this.Cursor = Cursors.WaitCursor;
          //  switch (this.tabControl1.SelectedTabIndex)
          //  {
          //      case 0:
          //          (pApplication as IFramework).ActivateMapControl();
          //          timer.Start();
          //          break;
          //      case 1:
          //          (pApplication as IFramework).ActivatePageLayoutControl();
          //          timer.Start();
          //          break;               
          //      case 2:
          //          (pApplication as IFramework).ActivateSceneControl();
          //          timer.Start();
          //          break;
          //      default:
          //          break;
          //  }

          //  (pApplication as IFramework).RaiseMapPageSwitchEvent();
          //  this.Cursor = Cursors.Default;
        }
        #endregion
         
        #region OnFormClosing
        protected override void OnFormClosing(FormClosingEventArgs e)
        {         
          
        }
        #endregion

        private void AppCommandTheme_Executed(object sender, EventArgs e)
        {
            ICommandSource source = sender as ICommandSource;
            if (source.CommandParameter is string)
            {
                eStyle style = (eStyle)Enum.Parse(typeof(eStyle), source.CommandParameter.ToString());
                StyleManager.ChangeStyle(style, Color.Empty);
                System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
                if (config.AppSettings.Settings["SystemStyle"] != null)
                {
                    config.AppSettings.Settings["SystemStyle"].Value = source.CommandParameter.ToString();
                    config.Save(System.Configuration.ConfigurationSaveMode.Modified);
                }
            }
            else if (source.CommandParameter is Color)
            {
                StyleManager.ColorTint = (Color)source.CommandParameter;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAbout_Click(object sender, EventArgs e)
        {           
            AboutBox frm = new AboutBox();
            frm.ShowDialog(this);                       
        }

        private void btnHelp_Click(object sender, EventArgs e)
        {
            string filePath = Application.StartupPath + "\\Help\\" + "用户手册.pdf";
            if (File.Exists(filePath))
            {
                try
                {
                    System.Diagnostics.Process.Start(filePath);
                }
                catch
                {
                    //ZJGIS.ADF.BaseClasses.ControlUtility.ShowInfomationMsgbox("找不到PDF文件的关联程序，无法打开！/n请安装Adobe Arcobat");
                }
            }
            else
            {
               // ZJGIS.ADF.BaseClasses.ControlUtility.ShowInfomationMsgbox("找不到帮助文件!");
            }
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
           // FrmSetting frmSetting = new FrmSetting(pApplication);
            //frmSetting.ShowDialog(this);
        }

        private void ReadLayoutConfig()
        {
            try
            {
                string strFile = Application.StartupPath +
                    (System.Configuration.ConfigurationManager.AppSettings.Get("Folder") == null || System.Configuration.ConfigurationManager.AppSettings.Get("Folder").Trim() == "" ? "" : ("\\" + System.Configuration.ConfigurationManager.AppSettings.Get("Folder"))) +
                    "\\Config\\LayoutConfig.xml";
                if (File.Exists(strFile) == false) return;
                XmlDocument doc = new XmlDocument();
                doc.Load(strFile);
                XmlNode node = doc.SelectSingleNode("//SelectedTabItem");
                if (node != null)
                {
                    for (int i = 0; i < ribbonControl1.Items.Count; i++)
                    {
                        RibbonTabItem item = ribbonControl1.Items[i] as RibbonTabItem;
                        if (item.Text == node.InnerText)
                        {
                            item.Checked = true;
                            break;
                        }
                    }
                }
                int index = 1;
                node = doc.SelectSingleNode("//QuickAccessItems");
                if (node != null)
                {
                    XmlNodeList nodelist= node.ChildNodes;
                    foreach (XmlElement subNode in nodelist)
                    {
                        if (subNode.Name == "功能点")
                        {
                            Type elementType = Type.GetType(subNode.Attributes["typename"].Value);
                            if (elementType != null)
                            {
                                object elementObj = Activator.CreateInstance(elementType);
                                BaseItem item = (pApplication as IFramework).BarManager.CommandPoolEx.FindBaseItem(elementObj.ToString());
                                //BaseItem item = (pApplication as IFramework).BarManager.CommandPoolEx.AddCommand(elementObj);
                                if (item != null)
                                {
                                  
                                    if (item is ButtonItem)
                                    {
                                        BaseItem item2 = item.Copy();
                                        (item2 as ButtonItem).ButtonStyle = DevComponents.DotNetBar.eButtonStyle.Default;
                                        (item2 as ButtonItem).ImagePosition = DevComponents.DotNetBar.eImagePosition.Left;
                                        (item2 as ButtonItem).ImageFixedSize = new Size(18, 18);
                                        ribbonControl1.QuickToolbarItems.Add(item2);
                                        item2.KeyTips = index.ToString();
                                        index++;
                                    }
                                   
                                }
                            }
                        }
                        else if (subNode.Name == "菜单")
                        {
                            if (subNode.ChildNodes.Count > 0)
                            {
                                ButtonItem btn = new ButtonItem();
                                btn.AutoCollapseOnClick = true;
                                btn.AutoExpandOnClick = true;
                                btn.Text = subNode.Attributes["名称"].Value.ToString();
                                XmlNodeList nodelist2 = subNode.ChildNodes;
                                foreach (XmlElement subNode2 in nodelist2)
                                {
                                    if (subNode2.Name == "功能点")
                                    {
                                        Type elementType = Type.GetType(subNode2.Attributes["typename"].Value);
                                        if (elementType != null)
                                        {
                                            object elementObj = Activator.CreateInstance(elementType);
                                           // BaseItem item = (pApplication as IFramework).BarManager.CommandPoolEx.AddCommand(elementObj);
                                            BaseItem item = (pApplication as IFramework).BarManager.CommandPoolEx.FindBaseItem(elementObj.ToString());
                                            if (item != null)
                                            {
                                                if (item is ButtonItem)
                                                {
                                                    BaseItem item2 = item.Copy();
                                                    (item2 as ButtonItem).ButtonStyle = DevComponents.DotNetBar.eButtonStyle.Default;
                                                    (item2 as ButtonItem).ImagePosition = DevComponents.DotNetBar.eImagePosition.Left;
                                                    (item2 as ButtonItem).ImageFixedSize = new Size(18, 18);
                                                    btn.SubItems.Add(item2);
                                                }
                                               
                                            }
                                        }
                                    }
                                }
                                ribbonControl1.QuickToolbarItems.Add(btn);
                            }
                        }
                    }
                 
                }
            }
            catch (System.Exception)
            {
            }
        }

        private void SaveLayoutConfig()
        {
            try
            {
                string strFile=Application.StartupPath+"\\Config\\LayoutConfig.xml";
                if (File.Exists(strFile) == false) return;
                XmlDocument doc = new XmlDocument();                
                doc.Load(strFile);
                XmlNode node= doc.SelectSingleNode("//SelectedTabItem");
                if (node != null)
                {
                    node.InnerText = ribbonControl1.SelectedRibbonTabItem.Text;
                }
                node = doc.SelectSingleNode("//QuickAccessItems");
                node.RemoveAll();
                foreach( BaseItem baseItem in   ribbonControl1.QuickToolbarItems)
                {
                    if (baseItem is Office2007StartButton) continue;
                    if (baseItem is QatCustomizeItem) continue;
                    if (baseItem is SystemCaptionItem) continue;
                    if (baseItem is ButtonItem && baseItem.Tag is Shine.Framework.ICommand )
                    {
                       XmlNode subNode= doc.CreateElement("功能点");
                       XmlAttribute att=  doc.CreateAttribute("名称");
                       att.Value = baseItem.Text;
                       XmlAttribute att2 = doc.CreateAttribute("typename");
                       att2.Value = baseItem.Tag.GetType().AssemblyQualifiedName;
                       subNode.Attributes.Append(att);
                       subNode.Attributes.Append(att2);
                       node.AppendChild(subNode);
                    }
                }
                doc.Save(strFile);              
            }
            catch (System.Exception)
            {

            }
        }
     
        private void dotNetBarManager1_AutoHideChanged(object sender, EventArgs e)
        {
           
        }

        private void lstPOI_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if(lstPOI.SelectedItems.Count==1)
            {
                Geometry geo = lstPOI.SelectedItems[0].Tag as Geometry;
                // m_sceneControl.Scene.Fly(geo, FlyingMode.FlyingTo)
                int idx=m_sceneControl.Scene.TrackingLayer.IndexOf("poi");
                if (idx >= 0) m_sceneControl.Scene.TrackingLayer.Remove(idx);
               
                GeoStyle style = new GeoStyle();
                style.FillForeColor = Color.Red;
                style.FillOpaqueRate = 100;
                geo.Style = style;
                m_sceneControl.Scene.TrackingLayer.Add(geo, "poi"); ;
             
                m_sceneControl.Scene.EnsureVisible(geo.Bounds, 1000);
                //switch(geo.Type)
                // {
                //     case GeometryType.GeoPoint:
                //         break;
                //     case GeometryType.GeoRegion:

                //         break;
                //     case GeometryType.GeoLine:
                //         break;
                //     default:
                //         break;

                // }
            }
        }
        
        void m_sceneControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.leftbar.Show();
                this.ribbonControl1.Show();
                this.barStauts.Show();
            }
        }

        private void office2007StartButton1_Click(object sender, EventArgs e)
        {
            //
        }

    }
}
   